<template>
  <div>
    <div>
      <van-nav-bar    fixed=true  placeholder=true title="账户与安全" left-text="" left-arrow @click-left="onClickFanHui">
      </van-nav-bar>
    </div>

    <div>
      <van class="jiange">
        <van-field
          v-model="username"
          label="用户名"
          placeholder=""
          disabled
          label-align="center"
          input-align="center"
        />
      </van>
    </div>
    <div>
      <van-cell-group class="jiange">
        <van-field
          v-model="oldPassword"
          label="旧密码"
          placeholder=""
          input-align="center"
          label-align="center"
        />
      </van-cell-group>
    </div>
    <div>
      <van class="jiange">
        <van-field
          v-model="newPassword"
          label="新密码"
          placeholder=""
          input-align="center"
          label-align="center"
        />
      </van>
    </div>
    <div style="margin: 16px">
      <van-button round block type="info" native-type="submit" @click="onClickSubmit"
        >提交</van-button
      >
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";
import md5 from 'js-md5';
export default {
  data() {
    return {
      username: "",
      oldPassword: "",
      newPassword: "",
      salt:"",
    };
  },

  created() {
    this.axios({
      method: "GET",
      url: "/aapi/me",
    }).then((response) => {
      this.username = response.data.username;
      this.axios({
        method: "GET",
        url: "/aapi/getSalt/"+this.username,
      }).then((response) => {
      this.salt = response.data+"";
    });
    });

  },

  methods: {
    onClickFanHui() {
      this.$router.push("/setting");
    },

    onClickSubmit() {
      let newSalt = Math.round(Math.random()*100)   + ""
      let formData = new FormData();
      formData.append("oldPassword", md5(this.oldPassword+this.salt));
      formData.append("newPassword", md5(this.newPassword+newSalt));
      formData.append("salt", newSalt);
      let confing = {
        headers: { "Content-Type": "multipart/form-data" },
      };
      this.axios
        .post("/aapi/xiugaimima", formData, confing)
        .then((res) => {
          if (res.status === 200) {
            Toast("修改成功");
          }
        })
        .catch((erroy) => {
          console.log(erroy.response.status);
          if (erroy.response.status === 405) {
            Toast("旧密码错误，请重新输入");
          }
        });
    },
  },
};
</script>

<style>
.jiange {
  margin-top: 10px;
}
</style>
